package org.wlgzs.moyue.service.servicelmpl;

import org.hibernate.boot.model.source.internal.hbm.CompositeIdentifierSingularAttributeSourceManyToOneImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.wlgzs.moyue.dao.BookDao;
import org.wlgzs.moyue.dao.MessageDao;
import org.wlgzs.moyue.entity.Book;
import org.wlgzs.moyue.entity.Comment;
import org.wlgzs.moyue.entity.Message;
import org.wlgzs.moyue.entity.User;
import org.wlgzs.moyue.service.MessageService;
import org.wlgzs.moyue.util.Result;
import org.wlgzs.moyue.util.ResultCode;

import javax.persistence.criteria.*;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Service
public class MessageServiceImpl implements MessageService {
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private BookDao bookDao;

    @Override
    public Result addMessage(Message message, HttpSession session) {
        User user = (User) session.getAttribute("user");
        message.setIsBrowse(0);
        message.setMessageDate(new Date());
        message.setUserId(user.getUserId());
        message.setRoleId(Integer.parseInt(user.getRoleId()));
        messageDao.save(message);
        message.setUserId(0);
        messageDao.save(message);
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public Result deleteMessage(long id) {
        if (messageDao.existsById(id)) messageDao.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public ModelAndView readMessage(long id, Model model) {
        Message message = messageDao.getOne(id);
        message.setIsBrowse(1);
        message = messageDao.save(message);
        model.addAttribute("message", message);
        return new ModelAndView("");
    }

    @Override
    public Result deleteMessages(long[] nums) {
        for (long messageId : nums) {
            messageDao.deleteById(messageId);
        }
        return new Result(ResultCode.SUCCESS);
    }

    @Override
    public ModelAndView allMessage(int page, Model model, HttpSession session, int isBrowsenum) {
        User user = (User) session.getAttribute("user");
        Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "messageDate"));
        Pageable pageable = new PageRequest(page - 1, 10, sort);

        //条件：指定用户，
        Specification<Message> specification = new Specification<Message>() {
            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Path userId = root.get("userId");
                Path isBrowse = root.get("isBrowse");
                if (user.getRoleId().equals("4")) {
                    return criteriaBuilder.equal(isBrowse, isBrowsenum);
                } else {
                    criteriaQuery.where(criteriaBuilder.equal(userId, user.getUserId()), criteriaBuilder.equal(isBrowse, isBrowsenum));
                    return null;
                }
            }
        };
        Page<Message> messagePage = messageDao.findAll(specification, pageable);
        model.addAttribute("page", messagePage.getNumber() + 1);
        model.addAttribute("pages", messagePage.getTotalPages());
        model.addAttribute("messages", messagePage.getContent());
        return new ModelAndView("");
    }

    @Override
    public Result changeMessage(long messageId, int audit, String content) {
        Message oldmessage = messageDao.getOne(messageId);
        Book book = bookDao.getOne(oldmessage.getBookId());
        Message message = new Message(0, oldmessage.getUserId(), oldmessage.getBookId(), null, new Date(), 0, 4);
        if (audit == 0) message.setMessage("您的书籍《" + book.getBookName() + "》审核未通过，理由如下：" + content);
        else message.setMessage("您的书籍《" + book.getBookName() + "》审核已通过，请继续努力！");
        messageDao.save(message);
        return new Result(ResultCode.SUCCESS);
    }


}
